/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.action.organization;

import apus.action.Action;
import apus.action.ActionResult;
import apus.entity.Organization;
import apus.entity.RealOrganization;
import apus.persistence.OrganizationDAO;
import apus.services.ServiceLocator;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author 21vek
 */
public class OrganizationSaveAction implements Action{

    @Override
    public String getName() {
        return "organization.save";
    }

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException ex) { }

        // if Save button have been pressed
        if (request.getParameter("saveButton") != null) {
            int id = Integer.parseInt(request.getParameter("id"));
            Organization organization = (id == 0) ? new RealOrganization() : ServiceLocator.getService(OrganizationDAO.class).read(id);

            // load data from request
            organization.setName(request.getParameter("name"));
            
            if (request.getParameter("bank")!=null){
                organization.setBankingDetails(request.getParameter("bank"));
            }
            
            if (request.getParameter("address")!=null){
                organization.setAddress(request.getParameter("address"));
            }

            OrganizationDAO organizationDAO = ServiceLocator.getService(OrganizationDAO.class);
            if (id != 0) {
                organizationDAO.update(organization); // update
                request.getSession().setAttribute("win", organization.getName()+" data was successfully updated");
            } else {
                organizationDAO.create(organization); // create
                request.getSession().setAttribute("win", organization.getName()+" was successfully created");
            }
        } else {
            request.getSession().setAttribute("fail", "Organization was not saved");
        }
        List<Organization> organizationList = ServiceLocator.getService(OrganizationDAO.class).findAll();
        request.setAttribute("organizationList", organizationList);
        return ActionResult.redirect("organization.list");
    }
    
}
